package com.lzb.newloan;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jungly.gridpasswordview.GridPasswordView;
import com.lzb.newloan.adapter.InvestPayAdapter;
import com.lzb.newloan.pojo.BorrowPersonPojo;
import com.lzb.newloan.utils.AlertDialog;
import com.lzb.newloan.utils.BaseActivity;
import com.lzb.newloan.utils.Config;
import com.lzb.newloan.utils.Formatdou;
import com.lzb.newloan.utils.HttpUtils;
import com.lzb.newloan.utils.TimeUtils;
import com.lzb.newloan.xlistview.XListView;
import com.lzb.newloan.xlistview.XListView.IXListViewListener;
import com.yintong.pay.utils.BaseHelper;
import com.yintong.pay.utils.Constants;
import com.yintong.pay.utils.EnvConstants;
import com.yintong.pay.utils.MobileSecurePayer;
import com.yintong.pay.utils.PayOrder;
import com.yintong.pay.utils.Rsa;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import static android.R.attr.data;
import static com.lzb.newloan.R.id.btn_neg;


/**
 * Created by Administrator on 2017/7/4.
 */

public class InvestPersonPayActivity extends BaseActivity implements
        IXListViewListener {

    private TextView ordertxt;
    private TextView money_all;
    private TextView money_bank;
    private TextView notice;
    private Button confirm_btn;
    private String userId, card, idno, mobilePhone, investName;
    private String MchntOrdId, totalmoney, AMT;
    private String jkid, timeString, money;
    private XListView invest_list;
    private ArrayList<BorrowPersonPojo> arrayList;
    private InvestPayAdapter adapter;
    private int num = 300;
    private TextView currentMoney;
    private LinearLayout currentMoneyLinear;
    private Button moneyConfirmBtn;
    private long lastTime = 0;
    private GridPasswordView gridPasswordView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invest_person_pay);
        initView();

        HttpUtils.doPostAsyn(Config.CHECKBORROWPERSON_CORD + "&jkid="
                + jkid + "&userid=" + userId, "", mHandler, Config.CODE_CHECKBORROWPERSON);

    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            num--;
            notice.setText(Html.fromHtml("请在" +"<font color=\"#FF532B\">"+num+"</font>"
                    + "秒之前完成操作倒计时结束后该借款用户将被释放"));
            mHandler.postDelayed(this, 1000);
            if (num < 0) {
                mHandler.sendEmptyMessage(100);
                mHandler.removeCallbacks(runnable);
            }
        }
    };

    private void cancle() {

        HttpUtils.doPostAsyn(Config.CANCLEBORROWPERSON_CORD + "&jkid="
                + jkid, "", mHandler, Config.CODE_CANCLEBORROWPERSON);
        mHandler.removeCallbacks(runnable);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        cancle();
    }

    private void initView() {
        SharedPreferences sp = getSharedPreferences("config", 0x0000);
        userId = sp.getString("userid", "");
        MchntOrdId = "xm" + userId + System.currentTimeMillis();
        Intent intent = getIntent();
        jkid = intent.getStringExtra("jkid");

        findViewById(R.id.backpress).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancle();
            }
        });
        TextView title_txt_center = (TextView) findViewById(R.id.title_txt_center);
        title_txt_center.setText("我要放款");
        ordertxt = (TextView) findViewById(R.id.order);
        ordertxt.setText("订单号："+MchntOrdId);

        currentMoney = (TextView) findViewById(R.id.current_money);
        currentMoneyLinear = (LinearLayout) findViewById(R.id.current_money_linear);
        moneyConfirmBtn = (Button) findViewById(R.id.money_confirm_btn);
        moneyConfirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long curTime = Calendar.getInstance().getTimeInMillis();
                if (curTime - lastTime > Config.MIN_CLICK_TIME) {
                    lastTime = curTime;
                    if (Double.parseDouble(money) < Double.parseDouble(totalmoney)) {
                        new AlertDialog(InvestPersonPayActivity.this).builder().setMsg("当前账户余额不足放款")
                                .setNegativeButton("确定", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                    }
                                }).show();
                    } else {


//                        AlertDialog ad = new AlertDialog(InvestPersonPayActivity.this);
//                        ad.builder().setMsg("当前投资放款金额为"+AMT+"元");
//                        ad.setNegativeButton("取消", new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//
//                            }
//                        });
//                        ad.setPositiveButton("确定",new View.OnClickListener(){
//                            @Override
//                            public void onClick(View v) {
//                                HttpUtils.doPostAsyn(Config.BANLANCE_CORD + "&jkid=" + jkid
//                                        + "&userid=" + userId + "&amt=" + AMT, "", mHandler, Config.CODE_BANLANCE);
//                            }
//                        });
//                        ad.show();

                        // 获取Dialog布局
                        View view = LayoutInflater.from(InvestPersonPayActivity.this).inflate(
                                R.layout.pay_alertdialog, null);

                        // 定义Dialog布局和参数
                        final Dialog dialog = new Dialog(InvestPersonPayActivity.this, R.style.AlertDialogStyle);
                        dialog.setContentView(view);
                        dialog.show();

                        view.findViewById(R.id.cancle).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });

                        gridPasswordView = (GridPasswordView) view.findViewById(R.id.pswView);

                        final Button btnNeg = (Button) view.findViewById(btn_neg);
                        btnNeg.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                btnNeg.setText("默认密码(123456)");
                            }
                        });
                        view.findViewById(R.id.btn_pos).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                HttpUtils.doPostAsyn(Config.CANCLEBORROWPERSON_CORD + "&jkid="
                                        + jkid, "", mHandler, Config.CODE_CANCLEPAYPWD);
                            }
                        });
                        final Button confirm_pay_btn = (Button) view.findViewById(R.id.comfirm_pay_btn);
                        confirm_pay_btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                HttpUtils.doPostAsyn(Config.BANLANCE_CORD + "&jkid=" + jkid
                                        + "&userid=" + userId + "&amt=" + AMT + "&payPassword=" + gridPasswordView.getPassWord(), "", mHandler, Config.CODE_BANLANCE);
                            }
                        });
                        //设置输入密码监听
                        gridPasswordView.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
                            //正在输入密码时执行此方法
                            public void onTextChanged(String psw) {

//                            tv.setText("正在输入密码...");

                            }

                            //输入密码完成时执行此方法
                            public void onInputFinish(String psw) {
                                confirm_pay_btn.setVisibility(View.VISIBLE);
//                            tv.setText("输入完成");
                            }
                        });

                    }

                } else {
                    new AlertDialog(InvestPersonPayActivity.this).builder().setMsg("请不要连续点击")
                            .setNegativeButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            }).show();

                }
            }
        });
        money_all = (TextView) findViewById(R.id.money_all);
        money_bank = (TextView) findViewById(R.id.money_bank);
        notice = (TextView) findViewById(R.id.notice);
        confirm_btn = (Button) findViewById(R.id.confirm_btn);
        confirm_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HttpUtils.doPostAsyn(Config.INVESTPAYSTART_CORD + "&jkid=" + jkid
                        + "&userid=" + userId + "&amt=" + AMT + "&payOrder=" + MchntOrdId, "", mHandler, Config.CODE_INVESTPAYSTART);
            }
        });

        invest_list = (XListView) findViewById(R.id.invest_person_list);
        arrayList = new ArrayList<BorrowPersonPojo>();

        adapter = new InvestPayAdapter(this, arrayList);
        invest_list.setAdapter(adapter);
        invest_list.setXListViewListener(this);
        invest_list.setPullLoadEnable(false);
        invest_list.setPullRefreshEnable(true);

        mHandler.postDelayed(runnable, 1000);
    }

    private void pay() {
        PayOrder order = null;
        // 卡前置方式
        if (TextUtils.isEmpty(card)) {
            Toast.makeText(InvestPersonPayActivity.this, "银行卡为空",
                    Toast.LENGTH_LONG).show();
            return;
        }
        order = constructPreCardPayOrder();
        // order.setShareing_data(((TextView)findViewById(R.id.share_money)).getText().toString().trim());
        String content4Pay = BaseHelper.toJSONString(order);
        // 关键 content4Pay 用于提交到支付SDK的订单支付串，如遇到签名错误的情况，请将该信息帖给我们的技术支持
        Log.i(BindCard2Activity.class.getSimpleName(), content4Pay);

        MobileSecurePayer msp = new MobileSecurePayer();
        boolean bRet = msp.payAuth(content4Pay, mHandler, Constants.RQF_PAY,
                InvestPersonPayActivity.this, false);

        Log.i(BindCard2Activity.class.getSimpleName(), String.valueOf(bRet));
    }


    private PayOrder constructPreCardPayOrder() {

        SimpleDateFormat dataFormat = new SimpleDateFormat(
                "yyyyMMddHHmmss");
        Date date = new Date();
        timeString = dataFormat.format(date);

        PayOrder order = new PayOrder();
        order.setBusi_partner("101001");//虚拟商品
        order.setNo_order(MchntOrdId);//唯一订单号
        order.setDt_order(timeString);//订单时间
        order.setName_goods("用户投资");
        order.setNotify_url(Config.INVEST_PAY_RESULTLL_CORD);
        // MD5 签名方式
//        order.setSign_type(PayOrder.SIGN_TYPE_MD5);
        // RSA 签名方式
        order.setSign_type(PayOrder.SIGN_TYPE_RSA);

        order.setValid_order("100");//订单有效时间

        order.setUser_id(userId);
        order.setId_no(idno);//身份证

        order.setAcct_name(investName);
        order.setMoney_order(AMT);

        // 银行卡卡号，该卡首次支付时必填
        order.setCard_no(card);
        // 银行卡历次支付时填写，可以查询得到，协议号匹配会进入SDK，
//        order.setNo_agree(((EditText) findViewById(R.id.agree_no)).getText()
//                .toString());

        // 风险控制参数
        order.setRisk_item(constructRiskItem());

        String sign = "";
        order.setOid_partner(EnvConstants.PARTNER);
        String content = BaseHelper.sortParam(order);
        // MD5 签名方式
//        sign = Md5Algorithm.getInstance().sign(content,
//                EnvConstants.MD5_KEY);

        // RSA 签名方式
        sign = Rsa.sign(content, EnvConstants.RSA_PRIVATE);
        order.setSign(sign);
        return order;
    }


    private String constructRiskItem() {
        JSONObject mRiskItem = new JSONObject();
        try {
            mRiskItem.put("user_info_bind_phone", mobilePhone);
            mRiskItem.put("user_info_dt_register", timeString);
            mRiskItem.put("frms_ware_category", "2010");
            mRiskItem.put("user_info_mercht_userno", userId);
//			mRiskItem.put("user_info_mercht_userno", UserId);
            mRiskItem.put("user_info_full_name", investName);
            mRiskItem.put("user_info_identify_state", 1);//用户是否实名认证
            mRiskItem.put("user_info_identify_type", 4);//实名认证方式（银行卡认证传1）
            mRiskItem.put("user_info_id_no", idno);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mRiskItem.toString();
    }

    private Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 100:
                    HttpUtils.doPostAsyn(Config.CANCLEBORROWPERSON_CORD + "&jkid="
                            + jkid, "", mHandler, Config.CODE_CANCLEBORROWPERSON);

                    break;
                case Config.CODE_INVESTPAYSTART:
                    try {
                        String result = msg.obj.toString();
                        JSONObject jsonResult = new JSONObject(result);
                        int err = jsonResult.getInt("error");
                        if (err == 0) {
                            pay();
                        } else {
                            showDialog(jsonResult.optString("msg"));
                        }
                    } catch (JSONException e2) {
                        // TODO Auto-generated catch block
                        e2.printStackTrace();
                    }
                    break;
                case Config.CODE_BANLANCE://余额放款
                    try {
                        String result = msg.obj.toString();
                        JSONObject jsonResult = new JSONObject(result);
                        int err = jsonResult.getInt("err");
                        if (err == 0) {
                            Intent intent = new Intent(InvestPersonPayActivity.this,
                                    InvestPersonActivity.class);
                            intent.putExtra("id", 1);
                            startActivity(intent);
                            finish();
                            Toast.makeText(InvestPersonPayActivity.this, "投资成功",
                                    Toast.LENGTH_SHORT).show();
                            mHandler.removeCallbacks(runnable);
                        } else {
//                            showDialog(jsonResult.optString("msg"));
//                            cancle();
//                            if(err==-4){
////                                startActivity(new Intent(InvestPersonPayActivity.this,InvestPersonActivity.class));
////                                finish();
//                                cancle();
//                            }
                            Toast.makeText(InvestPersonPayActivity.this, jsonResult.optString("msg"),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e2) {
                        // TODO Auto-generated catch block
                        e2.printStackTrace();

                    }
                    break;
                case Config.CODE_URL_ERROR:
                    Toast.makeText(InvestPersonPayActivity.this, "url错误",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Config.CODE_NET_ERROR:
                    Toast.makeText(InvestPersonPayActivity.this, "网络错误",
                            Toast.LENGTH_SHORT).show();
                    // if (time!=null) {
                    // time.cancel();
                    // }
                    break;
                case Constants.RQF_PAY:
                    String result = msg.obj.toString();
                    JSONObject objContent = BaseHelper.string2JSON(result);
                    String retCode = objContent.optString("ret_code");
                    String retMsg = objContent.optString("ret_msg");
                    String agreementno = objContent.optString("agreementno", "");//银行卡绑定协议号
                    String no_order = objContent.optString("no_order");
                    Double money_order = objContent.optDouble("money_order");

                    // 成功
                    if (Constants.RET_CODE_SUCCESS.equals(retCode)) {//交易成功
                        // TODO 卡前置模式返回的银行卡绑定协议号，用来下次支付时使用，此处仅作为示例使用。正式接入时去掉
                        Intent intent = new Intent(InvestPersonPayActivity.this,
                                InvestPersonActivity.class);
                        intent.putExtra("id", 1);
                        startActivity(intent);
                        finish();
                        Toast.makeText(InvestPersonPayActivity.this, "投资成功",
                                Toast.LENGTH_SHORT).show();
                        mHandler.removeCallbacks(runnable);
                    } else {
                        showDialog(objContent.optString("ret_msg"));
                        cancle();
                        MchntOrdId = "xm" + System.currentTimeMillis();
                    }


                    break;
                case Config.CODE_CHECKBORROWPERSON:
                    jkid = "";
                    try {
                        String results = msg.obj.toString();
                        JSONObject response = new JSONObject(results);
                        int error = response.getInt("error");
                        if (error == 0) {
                            JSONObject ininfo = response.getJSONObject("ininfo");
                            totalmoney = Formatdou.formatdou(ininfo.getDouble("totalmoney"));
                            AMT = totalmoney;
//                            AMT = "0.01";
                            money_all.setText(totalmoney);
                            money_bank.setText(ininfo.getString("inbankcard"));
                            card = ininfo.getString("inbankcardNo");//银行卡号
                            idno = ininfo.getString("idno");
                            investName = ininfo.getString("investName");
                            mobilePhone = ininfo.getString("mobilePhone");
                            JSONArray list = response.getJSONArray("list");
                            for (int i = 0; i < list.length(); i++) {
                                JSONObject object = (JSONObject) list.getJSONObject(i);
                                BorrowPersonPojo pojo = new BorrowPersonPojo();
                                if (jkid.equals("")) {
                                    jkid = object.optString("jkid");
                                } else {
                                    jkid = jkid + "," +  object.optString("jkid");
                                }


                                pojo.setUsername(object.getString("jkname") + "**");
                                int jk_date = object.getInt("jk_date");
                                if (jk_date == 1) {
                                    pojo.setDay("15天");
                                } else {
                                    pojo.setDay("30天");
                                }
                                pojo.setJk_money(object.getDouble("jk_rate"));//借款收益
                                pojo.setFk_money(object.getDouble("jk_money"));//借款
                                pojo.setFkTime(object.getString("jkcardname"));//借款银行
                                arrayList.add(pojo);

                            }
                            adapter.setArrayList(arrayList);
                            adapter.notifyDataSetChanged();
                            money = response.optString("investUsableSum");
                            if (TextUtils.isEmpty(money) || money.equals("0.00")) {
                                currentMoneyLinear.setVisibility(View.GONE);
                                moneyConfirmBtn.setVisibility(View.GONE);
                            } else {
                                currentMoneyLinear.setVisibility(View.VISIBLE);
                                moneyConfirmBtn.setVisibility(View.VISIBLE);
                                currentMoney.setText("当前可投资余额:" + money + "元");
                            }
                        } else {
                            new AlertDialog(InvestPersonPayActivity.this).builder().setMsg(response.getString("msg"))
                                    .setNegativeButton("确定", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            finish();
//                                            cancle();
                                        }
                                    }).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case Config.CODE_CANCLEPAYPWD:
                    try {
                        String result2 = msg.obj.toString();
                        JSONObject response = new JSONObject(result2);
                        int error = response.getInt("error");
                        if (error == 0) {
                            startActivity(new Intent(InvestPersonPayActivity.this, PayPwdActivity.class));
                            finish();
                            mHandler.removeCallbacks(runnable);
                        } else {
                            Toast.makeText(InvestPersonPayActivity.this, response.getString("msg"),
                                    Toast.LENGTH_SHORT).show();
                            mHandler.removeCallbacks(runnable);
                        }

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case Config.CODE_CANCLEBORROWPERSON:
//                    Toast.makeText(InvestPersonPayActivity.this, "投资项目已取消",
//                            Toast.LENGTH_SHORT).show();
                    try {
                        String result2 = msg.obj.toString();
                        JSONObject response = new JSONObject(result2);
                        int error = response.getInt("error");
                        if (error == 0) {
                            Intent intent = new Intent(InvestPersonPayActivity.this, InvestPersonActivity.class);
                            startActivity(intent);
                            finish();
                        } else {
                            Toast.makeText(InvestPersonPayActivity.this, response.getString("msg"),
                                    Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }

    };

    private void showDialog(String Message) {
        // TODO Auto-generated method stub
        new AlertDialog(InvestPersonPayActivity.this).builder().setMsg(Message)
                .setNegativeButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(InvestPersonPayActivity.this, InvestPersonActivity.class);
                        startActivity(intent);
                    }
                }).show();
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // list.clear();

            }
        }, 2000);
    }

    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

            }
        }, 2000);
    }

    protected void onLoad() {
        invest_list.stopRefresh();
        invest_list.stopLoadMore();
        invest_list.setRefreshTime(TimeUtils.getDate());
    }

    @Override
    public void processMessage(Message message) {

    }
}
